/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package finder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Alex
 */
public class FilterStage 
{
    private IPrimaryFilter primary;
    private ArrayList<ISecondaryFilter> secondaries;
    
    public FilterStage(IPrimaryFilter filter)
    {
        if(filter == null)
            throw new NullPointerException("primary filter can not be null.");
        primary = filter;
        secondaries = new ArrayList<>();
    }
    public void changePrimary(IPrimaryFilter value)
    {
        if(value != null)
            primary = value;
    }
    public boolean isResultLinkable()
    {
        return primary.producesLinks();
    }
    public void addSecondaryStage(ISecondaryFilter filter)
    {
        secondaries.add(filter);
    }
    public void clearSecondaryStage()
    {
        secondaries.clear();
    }
    public List<String> doStage(String url)
    {
        try 
        {
            String content = FilterStage.getHtmlString(url);
            List<String> results = primary.applyFilter(url, content);
            for (ISecondaryFilter s : secondaries)
                s.applyFilter(results);
            return results;
        } 
        catch (MalformedURLException | IllegalArgumentException ex) 
        {
            Logger.getLogger(FilterStage.class.getName()).log(Level.SEVERE, null, ex);
            return new ArrayList<>();
        }   
    }
    public static String getHtmlString(String url) throws MalformedURLException, IllegalArgumentException
    {
        URL u = new URL(url);
        try 
        {
            URLConnection connection = u.openConnection();
            String contentType = connection.getContentType();
            if(contentType == null || !contentType.toLowerCase().contains("text"))
               throw new IllegalArgumentException("Url content type could not be determined.");
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder sbuild = new StringBuilder();
            String line = reader.readLine();
            while(line != null)
            {
                sbuild.append(line);
                line = reader.readLine();
            }
            reader.close();
            return sbuild.toString();
        }
        catch (IOException ex) 
        {
            System.out.println("An IO error occured during a request to: " + url);
            Logger.getLogger(FilterDescription.class.getName()).log(Level.SEVERE, null, ex);
            return "";
        }
    }
}
